package com.ws.soa.consumer.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.base.Preconditions;
import com.ws.soa.consumer.common.enums.SmsActionEnum;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

/**
 * @author luobosi@2dfire.com
 * @since 2019-04-01
 */
@Slf4j
public class SmsUtils {

  private final static String ACCESS_ID = "LTAIc4ZKkQz1bk8n";

  private final static String ACCESS_SECRET = "G7j8FOZrjUWjiCffIBTsGZwYY4rAgm";

  private final static String REGION_ID = "cn-hangzhou";

  private final static String ALIYUN_DOMAIN = "dysmsapi.aliyuncs.com";

  /**
   * 发送短信, 多个手机号用,分割
   *
   * @param phoneNumbers      手机号，多个手机号用,分割
   * @param templateParamJson 参数
   * @param templateCode      模板 code
   */
  public static void sendSimpleMessage(String phoneNumbers,
                                       String templateParamJson,
                                       String templateCode) {

    Preconditions.checkArgument(StringUtils.isNotEmpty(phoneNumbers));

    Preconditions.checkArgument(templateCode != null);

    Preconditions.checkArgument(templateParamJson != null);

    String version = "2017-05-25";
    // 参数判空

    DefaultProfile profile = DefaultProfile.getProfile(
        REGION_ID,
        ACCESS_ID,
        ACCESS_SECRET);

    IAcsClient client = new DefaultAcsClient(profile);

    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain(ALIYUN_DOMAIN);
    request.setVersion(version);
    request.setAction(SmsActionEnum.SEND_SMS.getVal());
    request.putQueryParameter("RegionId", REGION_ID);
    request.putQueryParameter("PhoneNumbers", phoneNumbers);
    request.putQueryParameter("SignName", "波形计划");
    request.putQueryParameter("TemplateCode", templateCode);
    request.putQueryParameter("TemplateParam", templateParamJson);

    try {

      log.info("大于短信请求参数: {}", JSONObject.toJSONString(request));

      CommonResponse response = client.getCommonResponse(request);

      log.info("大于短信响应结果: {}", JSONObject.toJSONString(response));

    } catch (ServerException e) {

      log.error("server exception: {}", e);
    } catch (ClientException e) {

      log.error("client exception: {}", e);
    }

  }

}
